/*
 * Flashlib - QB9 common Flash library
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.qb9.flashlib.movieclip
{
	import flash.events.IEventDispatcher;
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.display.Stage;
	
	import com.qb9.flashlib.utils.ArrayUtil;
	import com.qb9.flashlib.interfaces.IDisposable;
	
	public class MovieClipManager implements IDisposable
	{		
		private var mc:MovieClip;
		private var list:Array = [];
		
		public function MovieClipManager(movieClip:MovieClip)
		{	
			mc = movieClip;
		}
				
		private function start():void
		{
			mc.addEventListener(Event.ENTER_FRAME, update);
		}

		private function stop():void
		{
			mc.removeEventListener(Event.ENTER_FRAME, update);
		}
		
		public function dispose():void
		{
			stop();
		}
		
		private function update(e:Event):void
		{				
			for each (var element:Object in list.slice())
				checkTrigger(Trigger(element));
			
			if(list.length == 0)
				stop();
		}
		
		private function checkTrigger(trigger:Trigger):void
		{
			if(trigger.condition.fulfilled(mc) == true)
			{
				trigger.action.run(mc);
				ArrayUtil.removeElement(list, trigger);
			}
		}
		
		public function when(trigger:Trigger):void
		{
			if(list.length == 0)
				start();
				
			list.push(trigger);
		}
		
		public function remove(trigger:Trigger):void
		{
			ArrayUtil.removeElement(list, trigger);
			
			if(list.length == 0)
				stop();
		}
	}
}
